package com.deer.wms.base.system.web.zhBusiness.business;

import com.deer.wms.base.system.model.bill.MaterialDetail;
import com.deer.wms.base.system.model.zh.BoxItemException;
import com.deer.wms.base.system.model.zh.Qualities;
import com.deer.wms.base.system.model.zh.Quality;
import com.deer.wms.base.system.service.bill.impl.MaterialDetailServiceImpl;
import com.deer.wms.base.system.service.bill.impl.MaterialInfoServiceImpl;
import com.deer.wms.base.system.service.zh.BoxItemExceptionService;
import com.deer.wms.base.system.service.zh.IExceptionGroupBoxService;
import com.deer.wms.base.system.service.zh.QualityService;
import com.deer.wms.common.core.controller.BaseController;
import com.deer.wms.common.core.domain.AjaxResult;
import com.deer.wms.common.core.page.TableDataInfo;
import com.deer.wms.common.core.result.CommonCode;
import com.deer.wms.common.core.result.Result;
import com.deer.wms.common.core.result.ResultGenerator;
import com.deer.wms.common.utils.poi.ExcelUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 异常方棒信息
 * @author 李帅辰
 * @date 2021/6/4 18:01
 * @return
 */
@Controller
@RequestMapping("/boxItemException")
public class BoxItemExceptionController extends BaseController {

    @Autowired
    private BoxItemExceptionService boxItemExceptionService;

    private String prefix = "boxItemException";

    @Autowired
    private MaterialDetailServiceImpl materialDetailService;

    @Autowired
    private MaterialInfoServiceImpl materialInfoService;

    @Autowired
    private QualityService qualityService;

    @Autowired
    private IExceptionGroupBoxService iExceptionGroupBoxService;


   /* @RequestMapping("editResult")
    public String editResult(){

        return prefix+"/editResult";
    }*/
    //批量修改
    @PostMapping("editall")
    @ResponseBody
    public AjaxResult editall(String ids, Integer result){
        String[] split = ids.split(",");
        for (String s:split
             ) {
            Quality q=new Quality();
            q.setCode(s);
            q.setResult(result);
            int i = qualityService.updateResult(q);
        }
        return toAjax(true);
    }

    /**
     *跳转显示页面
     * @return
     */
    @RequiresPermissions("boxItemException:view")
    @GetMapping
    public String boxItemException()
    {
        return prefix + "/boxItemException";
    }

    @RequiresPermissions("boxItemException:findList")
    @PostMapping("/findList")
    @ResponseBody
    public TableDataInfo findList(BoxItemException boxItemException) {
        startPage();
        List<BoxItemException> boxItemExceptionList = boxItemExceptionService.findBoxItemExceptionList(boxItemException);
        return getDataTable(boxItemExceptionList);
    }
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BoxItemException boxItemException) {

        List<BoxItemException> list = boxItemExceptionService.findBoxItemExceptionList(boxItemException);
        ExcelUtil<BoxItemException> util = new ExcelUtil<BoxItemException>(BoxItemException.class);
        return util.exportExcel(list, "异常区");
    }
    /**
     * 导出列表
     */
    //@RequiresPermissions("in:billInMaster:partExcel")
    @PostMapping("/partExcel")
    @ResponseBody
    public AjaxResult partExcel(@RequestParam String ids) {
        List<BoxItemException> byIds=new ArrayList();
        String[] split = ids.split(",");
        for (String s:split
        ) {
            BoxItemException  b=new BoxItemException ();
            b.setAreaId(Integer.parseInt(s));
            List<BoxItemException> list = boxItemExceptionService.findBoxItemExceptionList(b);
            for (BoxItemException bs:list
            ) {
                byIds.add(bs);
            }

        }
        // List<BillInSapDto> billInSapList = billInSapService.findBillInSapDtoList(billInSapCriteria);
        ExcelUtil<BoxItemException> util = new ExcelUtil<BoxItemException>(BoxItemException.class);
        return util.exportExcel(byIds, "异常区");
    }

    @RequiresPermissions("boxItemException:edit")
    @GetMapping("/editPage")
    public String editPage(){
        return prefix + "/edit";
    }

    /**
     * 修改异常区方棒信息
     * @author 申紫微
     * @date 9:39 2021/7/4
     * @params materialId 单晶id
     * @params materialBatchId 托号id
     * @params result 单晶质检结果
     * @return void
     **/
    @PostMapping("updateBoxItemException")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result updateBoxItemException(String materialId, String carrierId, Integer result){
        Result response = new Result();
        if (materialId == null){
            return ResultGenerator.genFailResult(CommonCode.PARAMETER_ERROR,"传入的晶棒id为空");
        }
        BoxItemException reqModel = new BoxItemException();
        reqModel.setMaterialId(materialId);
        // 根据传入的晶棒编码,查询异常晶棒的详细信息
        BoxItemException boxItemExdetail = boxItemExceptionService.findBoxItemException(reqModel);
        // 与原来数据相同，不需要修改数据库，直接返回成功
        if (carrierId.equals(boxItemExdetail.getCarrierId()) && result.equals(boxItemExdetail.getResult())){
            response = ResultGenerator.genSuccessResult();
        }else{
            // 托号应该是从方棒托中选出来的
            if(!carrierId.equals(boxItemExdetail.getCarrierId()) && !result.equals(boxItemExdetail.getResult())){
                // 查询晶棒明细，并更新
                MaterialDetail materialDetail = materialDetailService.findMaterialDetailByMaterialId(materialId);
                materialDetail.setCarrierId(carrierId);
                int res = materialDetailService.updateMaterial(materialDetail);

                Quality qualityModel = qualityService.findQualityByCode(materialId);
                qualityModel.setResult(result);
                int resNum = qualityService.updateQuality(qualityModel);
                if (res > 0 && resNum > 0){
                    response = ResultGenerator.genSuccessResult();
                }else {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    logger.error("修改异常区方棒信息失败，事务手动回滚");
                }
            }
            // 修改晶棒的托号信息，质检信息不修改
            if (!carrierId.equals(boxItemExdetail.getCarrierId()) && result.equals(boxItemExdetail.getResult())){
                // 查询晶棒明细，并更新
                MaterialDetail materialDetail = materialDetailService.findMaterialDetailByMaterialId(materialId);
                materialDetail.setCarrierId(carrierId);
                int res = materialDetailService.updateMaterial(materialDetail);
                if (res > 0){
                    response = ResultGenerator.genSuccessResult();
                }
            }
            // 修改质检情况，晶棒托不修改
            if (!result.equals(boxItemExdetail.getResult()) && boxItemExdetail.getCarrierId().equals(carrierId)){
                Quality qualityModel = qualityService.findQualityByCode(materialId);
                qualityModel.setResult(result);
                int i = qualityService.updateQuality(qualityModel);
                if (i > 0){
                    response = ResultGenerator.genSuccessResult();
                }
            }
        }
        return response;
    }

    /**
     * PC端组盘退货
     * @author 申紫微
     * @date 19:56 2021/7/6
     * @params materialId
     * @params carrierId
     * @return com.deer.wms.common.core.result.Result
     **/
    @PostMapping("/joinPlantForBack")
    @ResponseBody
    public Result joinPlantForBack(String materialId,String carrierId){
        Result result = new Result();

        boolean res = iExceptionGroupBoxService.joinPlantForBackAtPC(materialId,carrierId);

        return result;
    }

}
